package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;


@Api(tags = "员工管理")
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private HttpSession session;

    // 员工登录
    @ApiOperation(value = "员工登录")
    @PostMapping("/login")
    public ResultInfo logins(@RequestBody Employee loginEmployee) {  // 1.接收请求参数
        // 2.调用service登录
        Employee employee = employeeService.login(loginEmployee.getUsername(), loginEmployee.getPassword());
        // 3.返回结果
        return ResultInfo.success(employee);
    }

    // 员工退出
    @ApiOperation(value = "员工退出")
    @PostMapping("/logout")
    public ResultInfo logout() {
        // 1.自毁session
        session.invalidate();
        // 2.返回成功
        return ResultInfo.success();
    }

    // 员工列表查询
    @ApiOperation(value = "列表查询员工信息")
    @Cacheable(value = "employee",key = "#name")
    @GetMapping("/find")     //问号传参,这里不是路径传参
    public ResultInfo find(String name) {// 1.接收参数
        // 2.调用service
        List<Employee> list = employeeService.find(name);
        // 3.返回结果
        return ResultInfo.success(list);
    }

    //新增员工
    @ApiOperation(value = "新增员工信息")
    @CacheEvict(value = "employee",key ="#employee.id")
    @PostMapping
    public ResultInfo save(@RequestBody Employee employee) {

        employeeService.insertSave(employee);

        return ResultInfo.success();
    }

    //回显员工数据  --  根据ID查询员工数据
    @ApiOperation(value = "根据ID查询员工信息")
    @Cacheable(value = "employee",key = "#id")
    @GetMapping("/{id}")
    public ResultInfo findById(@PathVariable long id) {

        Employee employee = employeeService.findById(id);

        return ResultInfo.success(employee);
    }

    //修改员工信息
    @ApiOperation(value = "修改员工信息")
    @CacheEvict(value = "employee",allEntries = true)
    @PutMapping
    public ResultInfo updateEmp(@RequestBody Employee employee) {

        employeeService.updateEmployee(employee);

        return ResultInfo.success();
    }

}
